<template>
  <div class="list-page">
    <Row>
      <div class="toolbar">
        <al-cascader
          level="1"
          v-model="resItems"
          style="width: 180px; margin-right: 10px"
          @on-change="getArea"
          ref="address"
          placeholder="所属区域 默认全国"
        />
        <AgentSelectorSingle
          :agentId="bloc.form.agentId"
          :tagCount="1"
          style="width: 180px; margin-right: 10px"
          :agents="bloc.agentList"
          @on-change="(value) => (bloc.form.agentId = value)"
          v-if="tepee === '1'"
        ></AgentSelectorSingle>
        <Select
          v-model="bloc.form.modelName"
          placeholder="设备型号 默认全部型号"
          style="width: 180px; margin-right: 10px"
        >
          <Option v-for="item in bloc.modelList" :value="item.modelName" :key="item.id"
          >{{ item.modelName }}
          </Option>
        </Select>
        <Input
          placeholder="请输入要查询的设备序列号"
          v-model="bloc.form.deviceSn"
          style="width: 205px"
        />
        <Input
        placeholder="请输入要查询的联系人"
        v-model="bloc.form.name"
        style="width: 180px; margin-right: 10px"
        />
        <Input
          placeholder="请输入要查询的联系电话"
          v-model="bloc.form.phone"
          style="width: 180px; margin-right: 10px"
        />
        <Select
          v-model="bloc.form.state"
          style="width: 200px; margin-right: 10px"
          placeholder="请选择要查询的状态"
        >
          <Option v-for="item in bloc.form.stateList" :value="item.value" :key="item.value">{{ item.label }}</Option>
        </Select>
        <DatePicker
          type="daterange"
          placeholder="申请时间"
          format="yyyy/MM/dd"
          v-model="bloc.form.date"
          :editable="false"
          style="width: 200px; margin-right: 10px"
        ></DatePicker>
        <Button
          type="primary"
          icon="ios-search"
          style="margin: 0 10px"
          size="default"
          @click="bloc.load(1, bloc.paged.pageSize)"
        >查询
        </Button>
        <Button icon="md-refresh" @click="bloc.reset()">重置</Button>
      </div>
    </Row>
    <Row>
      <Table
        border
        style="width: 100%;"
        :loading="bloc.loading"
        :columns="columns"
        :data="bloc.paged.items"
      >
        <template slot-scope="{ row }" slot="action">
          <div style="white-space: nowrap">
            <Button
              size="small"
              style="margin-left: 5px; margin-right: 5px"
              @click="detailItem(row)"
              type="info"
            
            >详情
            </Button>

            <Button
              size="small"
              style="margin-left: 5px; margin-right: 5px;background-color: #fff618;color: black"
              @click="add(row)"
              v-if="row.state === '1' && row.ToDelete !== '1' "
            >添加工人
            </Button>
            <Button
                size="small"
                style="margin-left: 5px; margin-right: 5px"
                @click="allocation(row)"
                type="success"
                v-if=" row.state === '1' && row.ToDelete !== '1' "
            >分配
            </Button>
            <Button
              size="small"
              style="margin-left: 5px; margin-right: 5px"
              @click="delallocation(row)"
              type="warning"
              v-if="row.state === '2'&& row.ToDelete !== '1'"
            >取消分配
            </Button>
            <Button
               size="small"
               style="margin-left: 5px; margin-right: 5px"
               @click="trans(row)"
               type="primary"
               v-if=" row.state === '1' && row.ToDelete !== '1'"
            >流转
            </Button>
            <Button
              size="small"
              @click="removeItem(row,2)"
              v-if="row.state === '1' && row.ToDelete !== '1'"
              type="error"
            >删除
            </Button>
            <Button
              size="small"
              @click="removeItem(row,row.ToDelete)"
              v-if="row.state !== '4'&& row.ToDelete === '1'"
              type="error"
            >允许删除
            </Button>
            <Button
              size="small"
              @click="removeItem(row,0)"
              v-if=" row.state !== '4'&& row.ToDelete === '1'"
              type="error"
            >撤销删除
            </Button>
          </div>
        </template>
        <slot name="footer" slot="footer">
          <Page
            show-elevator
            show-total
            show-sizer
            :total="bloc.paged.itemCount"
            :current="bloc.paged.pageIndex"
            :page-size="bloc.paged.pageSize"
            :page-size-opts="[15, 30, 50, 100]"
            @on-change="(val) => bloc.load(val, bloc.paged.pageSize)"
            @on-page-size-change="(val) => bloc.load(bloc.paged.pageIndex, val)"
          />
        </slot>
      </Table>
    </Row>

    <Modal
      title="分配维修人员"
      v-model="bloc.allosymbol"
      class-name="vertical-center-modal"
      @on-cancel="cancel"
    >
      <p slot="header">
        <span>分配维修人员</span>
      </p>
      <div style="text-align: center">
          选择维修人员:
          <Select
            v-model="bloc.selectedWorker"
            filterable
            style="width: 200px; margin-right: 10px"
            placeholder="选择工人"
            clearable
          >
            <Option v-for="item in bloc.WorkerArray" :value="item.UserID" :key="item.UserID">{{ item.Name }}</Option>
          </Select>
      </div>
      <div slot="footer">
        <AppButton
          ref="save"
          type="primary"
          @click="workerSubmit(bloc.selectedWorker)"
        >确定</AppButton
        >
      </div>
    </Modal>
    <Modal
      title="将此售后单流转给其他经销商处理"
      v-model="bloc.dealersymbol"
      class-name="vertical-center-modal"
      @on-cancel="cancel"
    >
      <p slot="header">
        <span>将此售后单流转给其他经销商处理</span>
      </p>
      <div style="text-align: center">
        选择经销商:
        <Select
          v-model="bloc.selectedDealer"
          filterable
          style="width: 200px; margin-right: 10px"
          placeholder="选择经销商"
          clearable
        >
          <Option v-for="item in bloc.DealerArray" :value="item.DealerID" :key="item.DealerID">{{ item.DealerName }}</Option>
        </Select>
      </div>
      <div slot="footer">
        <AppButton
          ref="save"
          type="primary"
          @click="dealerSubmit(bloc.selectedDealer)"
        >确定</AppButton
        >
      </div>
    </Modal>
    <Modal
      title="添加工人"
      v-model="bloc.addsymbol"
      class-name="vertical-center-modal"
      @on-cancel="cancel"
    >
      <p slot="header">
        <span>添加工人</span>
      </p>
      <Form
        ref="formModel"
        :rules="ruleValidate"
        :model="bloc.worker"
        :label-width="100"
        label-position="right"
        style="margin-left: 90px"
      >
        <FormItem label="昵称:" prop="name" required>
          <Input
            placeholder="昵称"
            v-model="bloc.worker.name"
            style="width: 180px; margin-right: 10px"
          />
        </FormItem>
        <FormItem label="账户:" prop="phone" required>
          <Input
            placeholder="手机号"
            v-model="bloc.worker.phone"
            style="width: 180px; margin-right: 10px"
          />
        </FormItem>
        <FormItem label="密码:" prop="pw" required>
          <Input type="password"
                 autocomplete='new-password'
                 v-model="bloc.worker.pw"
                 placeholder="请输入6~12位密码"
                 style="width: 180px; margin-right: 10px"/>
        </FormItem>
        <FormItem label="确认密码:" prop="cpw" required>
          <Input type="password"
                 autocomplete='new-password'
                 v-model="bloc.worker.cpw"
                 placeholder="请再次输入密码"
                 style="width: 180px; margin-right: 10px"/>
        </FormItem>
      </Form>

      <div slot="footer">
        <AppButton
          ref="save"
          type="primary"
          @click="save('formModel')"
        >确定</AppButton
        >
      </div>
    </Modal>

  </div>
</template>

<script lang="ts">
    import { Component, Vue } from 'vue-property-decorator';
    import { Route } from 'vue-router';
    import { MaintainBloc } from '@/view/service/maintain/MaintainBloc';
    import { MainTain } from '@/base/model/MainTain';
    import { formatDate } from '@/base/util/Dates';
    import { Validation } from '@/base/Validation';
    import { Resources } from '@/base/Resources';
    import ChangeAccountPwd from '@/component/ChangeAccountPwd.vue';
    import { isEmpty } from '@/base/util/Strings';
    import { getValidatePhone, getValidatePsd1 } from '@/base/util/Validate';
    import { AppButton } from '@/type/AppButton';
    import AgentSelector from '@/component/AgentSelector.vue';
    import { store } from '@/store/Store';
    import AgentSelectorSingle from '@/component/AgentSelectorSingle.vue';

    const columns = (bloc: MaintainBloc) => [
        {
            title: '设备型号',
            render: (h: any, params: any) => {
                return h('span', {
                    domProps: {
                        innerText: params.row.PM?params.row.PM:params.row.ProModel
                    }
                });
            },
            align: 'left',
            width: 150,
            tooltip: true
        },
        {
            title: '所属经销商',
            key: 'dealerName',
            align: 'left',
            width: 100,
            tooltip: true
        },
        {
            title: '设备序列号',
            key: 'SN',
            align: 'left',
            width: 200,
            tooltip: true
        },
        {
            title: '购买时间',
            render: (h: any, params: any) => {
                return h('span', {
                    domProps: {
                        innerText: formatDate(
                            new Date(params.row.buyTime),
                            'yyyy-MM-dd'
                        )
                    }
                });
            },
            width: 160,
            align: 'left',
            tooltip: true
        },
        {
            title: '申请时间',
            render: (h: any, params: any) => {
                return h('span', {
                    domProps: {
                        innerText: formatDate(
                            new Date(params.row.applyTime),
                            'yyyy-MM-dd hh:mm:ss'
                        )
                    }
                });
            },
            width: 160,
            align: 'left',
            tooltip: true
        },
        {
            title: '联系人',
            key: 'name',
            align: 'left',
            width: 100,
            tooltip: true
        },
        {
            title: '联系电话',
            key: 'tel',
            align: 'left',
            width: 200,
            tooltip: true
        },
        {
            title: '维修进度',
            key: 'state',
            render: (h: any, params: any) => {
                return h('span', {
                    domProps: {
                        innerText: params.row.state === '0' ? '已取消'
                                  : params.row.state === '1' ? '待分配'
                                  : params.row.state === '2' ? '待接单'
                                  : params.row.state === '4' ? '已完成'
                                  : params.row.state === '5' ? '已接单待预约'
                                  : params.row.state === '6' ? '已预约待上门'
                                  : '维修中'
                    }
                });
            },
            align: 'left',
            width: 200,
            tooltip: true
        },
        {
            title: '操作',
            slot: 'action',
            width: 350,
            align: 'left',
            fixed: 'right'
        }
    ];

    @Component({
        components: {AgentSelectorSingle, ChangeAccountPwd, AgentSelector}
    })
    export default class extends Vue {
row: any;
        beforeRouteEnter(to: Route, from: Route, next: (vm: any) => void) {
            next((vm) => {
                vm.bloc
                    .load(vm.bloc.paged.pageIndex, vm.bloc.paged.pageSize)
                    .catch((e) => {
                        vm.$Message.error('操作错误');
                    });
                vm.bloc.getAllAngent(1, 1000, 'DESC');
                vm.bloc.getAllModel(1, 1000, undefined, 'DESC', undefined);
            });
        }

        bloc: MaintainBloc = new MaintainBloc();
        Validation = Validation;
        Resources = Resources;
        columns = columns(this.bloc);
        NowID = 0;
        DealerID = 0;
        $refs!: {
            save: AppButton
            sort: HTMLFormElement;
            editSort: HTMLFormElement;
            formModel: HTMLFormElement
        };
        get tepee() {
            if (store.state.user.tepee === '2') {
                // 隐藏经销商栏目
                this.columns = this.columns.filter(
                    (column) => column.key !== 'dealerName'
                );
            }
            return store.state.user.tepee;
        }
        validateRepeatPassword = (rule: any, value: string, callback: any) => {
            isEmpty(this.bloc.worker.cpw) ||
            this.bloc.worker.pw !== this.bloc.worker.cpw
                ? callback(new Error('前后密码输入不一致。')) : callback();
        };
        validatePhone = (rule: any, value: string, callback: any) => {
            if (isEmpty(value)) return callback(new Error('手机号码不能为空'));
            if (!getValidatePhone(value)) return callback(new Error('请输入正确的手机号码'));
            return callback();
        };
        validatePsd = (rule: any, value: string, callback: any) => {
            if (isEmpty(value)) return callback(new Error('密码不能为空'));
            if (!getValidatePsd1(value)) return callback(new Error('密码由字母、数字、下划线组成且长度为6-20'));
            return callback();
        };
        ruleValidate = {
            name: [
                {required: true, message: '请填写昵称', trigger: 'blur'}
            ],
            pw: [
                {required: true, validator: this.validatePsd, trigger: 'blur'}
            ],
            phone: [
                {required: true, validator: this.validatePhone, trigger: 'blur'}
            ],
            cpw: [
                {validator: this.validateRepeatPassword, trigger: 'change'}
            ]
        };
        cancel() {
            this.bloc.selectedWorker = 0;
            this.bloc.selectedDealer = 0;
            this.NowID = 0;
            this.DealerID = 0;
            this.bloc.worker = {
                name: '',
                phone: '',
                pw: '',
                cpw: ''
            }
        }
        detailItem(dataItem: MainTain) {
            const num:string = JSON.stringify(dataItem);
            this.$router.push({
                path: `/service/maintain/detail`,
                query: {param: num}});
        }
        allocation(dataItem: MainTain) {
            this.NowID = dataItem.id;
            this.bloc.allocation(dataItem.dealerid);
        }
        add(dataItem: MainTain) {
            this.DealerID = dataItem.dealerid;
            this.bloc.addsymbol = true;
        }
        resItems: any = [];
        getArea(data) {
            if (data.length > 0) {
                this.bloc.form.provinceId = data[0].code;
                this.bloc.form.province = data[0].name;
                if (data.length > 1) {
                    this.bloc.form.cityId = data[1].code;
                    this.bloc.form.city = data[1].name;
                }
            }
        }
        save(name) {
            this.$refs[name].validate(valid => {
              console.log(valid);
              if (valid) {
                  this.bloc.save(this.DealerID).then(res => {
                      this.$Message.success('保存成功');
                      this.bloc.loading = false;
                      this.bloc.addsymbol = false;
                      this.cancel();
                  }).catch(err => {
                      this.bloc.loading = false;
                      this.bloc.addsymbol = false;
                      this.$Message.error(err.message || '保存失败');
                  });
              }
            });
        }
        workerSubmit(UserID) {
            this.bloc.workerSubmit(UserID, this.NowID).then((res) => {
                this.$Message.success('分配维修人员成功');
                this.bloc.allosymbol = false;
                this.bloc.reset();
            }).catch((res) => {
                this.bloc.allosymbol = false;
                this.$Message.error(res.message);
            });
        }
        dealerSubmit(DealerID) {
            this.bloc.dealerSubmit(DealerID, this.NowID).then((res) => {
                this.$Message.success('流转下级经销商成功');
                this.bloc.dealersymbol = false;
                this.bloc.reset();
            }).catch((res) => {
                this.bloc.dealersymbol = false;
                this.$Message.error(res.message);
            });
        }
        delallocation(dataItem: MainTain) {
            this.$Modal.confirm({
                title: '提示',
                content: '确认取消后将无法恢复！还要继续吗？',
                okText: '确认',
                cancelText: '取消',
                onOk: () => {
                    this.bloc.deldelallocation(dataItem.id, dataItem.dealerid).then((res) => {
                        this.$Message.success('取消成功');
                        this.bloc.reset();
                    }).catch((res) => {
                        this.$Message.error(res.message);
                    })
                }
            });
        }
        trans(dataItem: MainTain) {
            this.NowID = dataItem.id;
            this.bloc.trans(dataItem.dealerid);
        }
        removeItem(dataItem: MainTain, sym) {
            this.$Modal.confirm({
                title: '提示',
                content: '确认后该操作将无法恢复！还要继续吗？',
                okText: '确认',
                cancelText: '取消',
                onOk: () => {
                    this.bloc.delPostsale(dataItem.id, dataItem.dealerid, sym).then((res) => {
                        this.$Message.success('处理成功');
                        this.bloc.reset();
                    }).catch((res) => {
                        this.$Message.error(res.message);
                    })
                }
            });
        }
    }
</script>

<style lang="less">
</style>
